from http import HTTPStatus
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework import serializers
from rest_framework.views import APIView

from apps.ormlab.models import Book, Author, Tags
# from utils.permission import PublicRole


# Create your views here.
class Home(APIView):
    def get(self, request):
        return Response({"message": "Hello, ORM Lab Home!"})
    


class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = "__all__"

class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer
    # permission_classes = [PublicRole]

class TagsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tags
        fields = "__all__"

class TagsViewSet(viewsets.ModelViewSet):
    queryset = Tags.objects.all()
    serializer_class = TagsSerializer

class BookSerializer(serializers.ModelSerializer):
    # tags_details = TagsSerializer(many=True, source="tags", read_only=True)
    tags = TagsSerializer(many=True, read_only=True)
    
    # 在update时有问题
    # author_details = AuthorSerializer(source="author", read_only = True)
    author = AuthorSerializer(read_only=True)
    class Meta:
        model = Book
        depth = 1
        # fields = ["id", "name", "author_details", "description", "published_date", "tags"]
        fields = '__all__'
    
    def create(self, validated_data):
        # print("BookSerializer create ", validated_data)
        # print(self.initial_data, type(self.initial_data))
        author_id = self.initial_data.get("author") # type: ignore
        if author_id:
            try:
                author = Author.objects.get(id=author_id)
                validated_data["author"] = author
            except Author.DoesNotExist:
                raise ValidationError(f"author id: {author_id} does not exist", code=HTTPStatus.NOT_FOUND)
                # return JsonResponse(code=HTTPStatus.NOT_FOUND, 
                #                     message=f"author id: {author_id} does not exist", 
                #                     status = ResponseStatus.ERROR)
        else:
            raise ValidationError("author is required", code=HTTPStatus.NOT_FOUND)
            # return JsonResponse(code=HTTPStatus.NOT_FOUND, 
            #                         message="author is required", 
            #                         status = ResponseStatus.ERROR)

        tags_ids = self.initial_data.get("tags") # type: ignore
        if tags_ids:
            tags_obj_list = []
            for tag_id in tags_ids:
                tags_obj_list.append( Tags.objects.get(id=tag_id))
            validated_data["tags"] = tags_obj_list

        return super().create(validated_data)

    def update(self, instance, validated_data):
        # print("BookSerializer update ", instance.__dict__)
        # print("BookSerializer update ", validated_data)
        # print(self.initial_data, type(self.initial_data))
        author_id = self.initial_data.get("author") # type: ignore
        if author_id:
            author = Author.objects.get(id=author_id)
            validated_data["author"] = author
        # print(">> BookSerializer update ", validated_data)
        tags_ids = self.initial_data.get("tags") # type: ignore
        if tags_ids:
            tags_obj_list = []
            for tag_id in tags_ids:
                tags_obj_list.append( Tags.objects.get(id=tag_id))
            validated_data["tags"] = tags_obj_list

        return super().update(instance, validated_data)


class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

